package controllers

import (
	"github.com/gin-gonic/gin"
	"mytest/util"
	"net/http"
)

type LoginController struct {
}

func (t *LoginController) Index(c *gin.Context) {
	// 网页
	if c.Request.Method == http.MethodGet {
		c.HTML(http.StatusOK, "layout/main.html", gin.H{
			"title":          "main.html title",
			"content_before": "content 内容上部分",
			"content_text":   "content 内容部分",
			"content_after":  "content 内容下部分",
		})
		c.Abort()
		return
	}

	// 检查用户登录代码
	// ...

	// session
	session, err := util.SessionStart(c.Writer, c.Request)
	if err != nil {
		panic(err)
	}

	session.Set("uid", "10008")
	err = session.Save()
	if err != nil {
		panic(err)
	}

	// 跳转到登录成功页
	c.Redirect(http.StatusMovedPermanently, "/users/add")
}

func (t *LoginController) Captcha(c *gin.Context) {
	id, b64s, err := util.CreatCaptcha("math")
	if err != nil {
		c.JSON(http.StatusOK, util.ReturnData(500, err.Error(), nil))
		return
	}
	code := 0
	var data interface{}
	if err != nil {
		code = 1
		data = ""
	} else {
		data = map[string]string{"id": id, "value": b64s}
	}
	c.JSON(http.StatusOK, util.ReturnData(code, "ok", data))
}

func (t *LoginController) VerifyCaptcha(c *gin.Context) {
	var formHelper util.FormHelper
	params := [][]string{
		{"captcha_id", "string", "required"},
		{"verify_code|验证码", "string", "required"},
	}
	data, err := formHelper.Params(params, c)
	if err != nil {
		c.JSON(http.StatusOK, util.ReturnData(500, err.Error(), nil))
		return
	}
	verify := util.VerifyCaptcha(data["captcha_id"].(string), data["verify_code"].(string))
	if !verify {
		c.JSON(http.StatusOK, util.ReturnData(1, "验证码错误", nil))
		return
	}
	c.JSON(http.StatusOK, util.ReturnData(0, "ok", data))
}
